import tl = require('azure-pipelines-task-lib/task');
import { exec } from 'child_process';

async function runPowershell_backup(params: string) {
    const sourceFolder: string | undefined = tl.getInput('sourceFolder', false);
    console.log('sourceFolder', sourceFolder);
    const targetFolder: string | undefined = tl.getInput('targetFolder', false);
    console.log('targetFolder', targetFolder);
    const backupVersionName: string | undefined = tl.getInput('backupVersionName', false);
    const maxBackupCount: string | undefined = tl.getInput('maxBackupCount', false);
    let backupIgnore: string | undefined = tl.getInput('backupIgnore', false);
    console.log('typeof(backupIgnore)', typeof (backupIgnore));
    console.log('backupIgnore', backupIgnore);
    if(backupIgnore){
        backupIgnore = backupIgnore.trim().split('\n').map(line => line.trim()).join(',')
    }
    console.log("---backupIgnore---format---",backupIgnore)

    // PowerShell path
    const scriptPath = __dirname + "\\" + "backup.ps1";
    console.log(scriptPath);
    // PowerShell
    const command = `powershell.exe -File ${scriptPath} -sourceFolder ${sourceFolder} -targetFolder ${targetFolder} -backupVersionName ${backupVersionName} -maxBackupCount ${maxBackupCount} -backupIgnore ${backupIgnore}`;
    console.log('command', command);


    // child_process.exec() run PowerShell
    exec(command, (error, stdout, stderr) => {
        if (error) {
            console.error(`Error executing PowerShell script: ${error}`);
            return;
        }

        // log
        console.log(stdout);
        if (stderr) console.error('PowerShell Script Errors:', stderr);
    });
}


async function run() {
    try {
        runPowershell_backup("")
    }
    catch (err) {
        tl.setResult(tl.TaskResult.Failed, "error_");
    }
}

run();